//
//  ZLInteractiveTransition.m
//  AnimationDemo
//
//  Created by jiaozenglian on 2020/7/12.
//  Copyright © 2020 Jiaozl. All rights reserved.
//

#import "ZLInteractiveTransition.h"

@interface ZLInteractiveTransition ()
@property (nonatomic, weak) id<UIViewControllerContextTransitioning> transitionContext;
@property (nonatomic, strong, readonly) UIPanGestureRecognizer *gestureRecognizer;
@property (nonatomic, readonly) UIRectEdge edge;
@end

@implementation ZLInteractiveTransition

- (instancetype)initWithGestureRecognizer:(UIPanGestureRecognizer *)gestureRecognizer edgeForDragging:(UIRectEdge)edge
{
    NSAssert(edge == UIRectEdgeTop || edge == UIRectEdgeBottom ||
             edge == UIRectEdgeLeft || edge == UIRectEdgeRight,
             @"edgeForDragging must be one of UIRectEdgeTop, UIRectEdgeBottom, UIRectEdgeLeft, or UIRectEdgeRight.");
    if (self = [super init]) {
        _gestureRecognizer = gestureRecognizer;
        _edge = edge;
        [_gestureRecognizer addTarget:self action:@selector(_handleGesture:)];
    }
    return self;
}

- (instancetype)init
{
    @throw [NSException exceptionWithName:NSInvalidArgumentException reason:@"Use -initWithGestureRecognizer:edgeForDragging:" userInfo:nil];
}

// 手势触发该方法
-(void)_handleGesture:(UIPanGestureRecognizer *)gestureRecognizer
{
    switch (gestureRecognizer.state) {
        case UIGestureRecognizerStateBegan:
            break;
        case UIGestureRecognizerStateChanged:
            // 调用updateInteractiveTransition来更新动画进度
            // 里面嵌套定义 percentForGesture 方法计算动画进度
            [self updateInteractiveTransition:[self percentForGesture:gestureRecognizer]];
            break;
        case UIGestureRecognizerStateEnded:
        case UIGestureRecognizerStateCancelled:
            // 判断手势位置，要大于一半,就完成这个转场，要小于一半就取消
            if([self percentForGesture:gestureRecognizer] < 0.5f || gestureRecognizer.state == UIGestureRecognizerStateCancelled ) { // 取消交互转场
                [self cancelInteractiveTransition];
            } else { // 完成交互转场
                [self finishInteractiveTransition];
            }
            break;
        default:
            break;
    }
}

// 计算动画进度
- (CGFloat)percentForGesture:(UIPanGestureRecognizer *)gesture
{
    UIView *transitionContainerView = gesture.view;
    // 手势滑动 获取滑动向量
    CGPoint locationInSourceView = [gesture translationInView:transitionContainerView];
//    CGFloat width = CGRectGetWidth(transitionContainerView.bounds);
//    CGFloat height = CGRectGetHeight(transitionContainerView.bounds);
    CGFloat width = [self baseSize].width;
    CGFloat height = [self baseSize].height;
    if (self.edge == UIRectEdgeRight) {
        return (-locationInSourceView.x) / width;
    } else if(self.edge == UIRectEdgeLeft) {
        return locationInSourceView.x / width;
    } else if(self.edge == UIRectEdgeBottom) {
        return (-locationInSourceView.y) / height;
    } else if (self.edge == UIRectEdgeTop) {
        return locationInSourceView.y / height;
    } else {
        return 0.f;
    }
}

- (CGSize)baseSize
{
    UIViewController *fromViewController = [self.transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    UIViewController *toViewController = [self.transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    
    UIView *fromView = [self currentViewControllerWithRoot:fromViewController].view;
    UIView *toView = [self currentViewControllerWithRoot:toViewController].view;
    
    return CGSizeMake(MIN(fromView.bounds.size.width, toView.bounds.size.width), MIN(fromView.bounds.size.height, toView.bounds.size.height));
}

// 获取手机当前显示的ViewController
- (UIViewController*)currentViewControllerWithRoot:(UIViewController *)rootVc
{
    UIViewController *vc = rootVc;
    while(1) {
        if ([vc isKindOfClass:[UITabBarController class]] ) {
            vc = ((UITabBarController*)vc).selectedViewController;
        }
        if ([vc isKindOfClass:[UINavigationController class]] ) {
            vc = ((UINavigationController*)vc).visibleViewController;
        }
        if (vc.presentedViewController ) {
            vc = vc.presentedViewController;
        } else {
            break;
        }
    }
    return vc;
}


// MARK: - UIViewControllerInteractiveTransitioning
/**
 前面代理通过 interactionControllerForPresentation 方法获取交互控制器的时候，手势返回的就是本类的实例，这个时候就会调用这个方法
 */
- (void)startInteractiveTransition:(id<UIViewControllerContextTransitioning>)transitionContext
{
    [super startInteractiveTransition:transitionContext];
    self.transitionContext = transitionContext;
}

- (void)dealloc
{
    NSLog(@"%s", __func__);
}

@end
